package com.tech.koufu.ui.view;


import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.tech.koufu.MainActivity;
import com.tech.koufu.MyApplication;
import com.tech.koufu.R;    
import com.tech.koufu.model.MarketStock;
import com.tech.koufu.tools.CookieStringRequest;
import com.tech.koufu.tools.Statics;
import com.tech.koufu.ui.activity.MarketDeatilActivity;
import com.tech.koufu.ui.adapter.MarketAdapter; 

import extras.com.handmark.pulltorefresh.library.PullToRefreshBase;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import extras.com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import extras.com.handmark.pulltorefresh.library.PullToRefreshListView;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable; 
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup; 
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

/**
 * 行情 fragment
 * 
 * @author jl_luo
 * 
 */
@SuppressLint("ResourceAsColor")
public class MarketContentFragment extends BaseContainerFragment implements OnClickListener{
	private static final String TAG = MarketContentFragment.class.getName();

	private View rootView;
	private PullToRefreshListView mPullToRefreshListView;
	private ListView actualListView;
	private MarketAdapter mAdapter;
	private ArrayList<MarketStock> datas;
	private ArrayList<MarketStock> topdatas;
	private RequestQueue mQueue; 
	private MyApplication myApp;
	CookieStringRequest stringRequest;
	private View lv_top;
	private TextView tv_sh_name,tv_sz_name,tv_cy_name,
	tv_sh_price,tv_sz_price,tv_cy_price,
	tv_sh_increment,tv_sz_increment,tv_cy_increment;
	private LinearLayout ly_sh,ly_sz,ly_cy;
//	private Spinner sp_market;
	private String stocktype = "SH";
	private	String zqlb= "A";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
		if (rootView == null) {Log.d(TAG, "~~~~~MarketContentFragment~onCreateView~~~~~~~~~~");
		rootView = inflater.inflate(R.layout.activity_main_market, container, false);
		initView();
		initData();
		}else{
			Log.d(TAG, "~~~~no~MarketContentFragment~onCreateView~~~~~~~~~~");
		}
		ViewGroup parent = (ViewGroup) rootView.getParent();
		if (parent != null) {
			parent.removeView(rootView);
		}
		
		return rootView; 
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(myApp.isLogin){
			MainActivity mainActivity = (MainActivity)getActivity();
			mainActivity.showContent();
		}
	}
	
	private void initView() {  
		myApp = (MyApplication)getActivity().getApplication();
		mPullToRefreshListView = (PullToRefreshListView) rootView.findViewById(R.id.pull_refresh_grid);		
		actualListView = mPullToRefreshListView.getRefreshableView();
		registerForContextMenu(actualListView);
		lv_top = LayoutInflater.from(getActivity().getApplicationContext()).inflate(R.layout.lv_item_markethead, null);

		tv_sh_name = (TextView)lv_top.findViewById(R.id.tv_sh_name);
		tv_sz_name = (TextView)lv_top.findViewById(R.id.tv_sz_name);
		tv_cy_name = (TextView)lv_top.findViewById(R.id.tv_cy_name);

		tv_sh_price = (TextView)lv_top.findViewById(R.id.tv_sh_price);
		tv_sz_price = (TextView)lv_top.findViewById(R.id.tv_sz_price);
		tv_cy_price = (TextView)lv_top.findViewById(R.id.tv_cy_price);

		tv_sh_increment = (TextView)lv_top.findViewById(R.id.tv_sh_increment);
		tv_sz_increment = (TextView)lv_top.findViewById(R.id.tv_sz_increment);
		tv_cy_increment = (TextView)lv_top.findViewById(R.id.tv_cy_increment);

		ly_sh = (LinearLayout)lv_top.findViewById(R.id.ly_sh);
		ly_sz = (LinearLayout)lv_top.findViewById(R.id.ly_sz);
		ly_cy = (LinearLayout)lv_top.findViewById(R.id.ly_cy);
		ly_sh.setOnClickListener(this);
		ly_sz.setOnClickListener(this);
		ly_cy.setOnClickListener(this);

		actualListView.addHeaderView(lv_top,null,false);
		actualListView.setAdapter(mAdapter);
		actualListView.setOnItemClickListener(itemClick);
//		sp_market = (Spinner)rootView.findViewById(R.id.sp_market);
//		ArrayAdapter<String> adapter = new ArrayAdapter<String>(MarketContentFragment.this.getActivity(),
//					R.array.spinner_market, android.R.layout.simple_spinner_item);
//		sp_market.setAdapter(adapter);
		MainActivity ma =(MainActivity)getActivity();
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
				R.layout.my_spinner_title,spinnerData());
		adapter.setDropDownViewResource(R.layout.my_spinner);
		ma.sp_market.setAdapter(adapter);
		ma.sp_market.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				switch (position) {
				case 0:
					stocktype = "SH";
					zqlb = "A";
					break;
				case 1:
					stocktype = "SZ";
					zqlb = "A";
					break;
				case 2:
					stocktype = "SZ";
					zqlb = "C";
					break;
				default:
					break;
				}
				mPullRefreshList();
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState); 
		//		initData();
	}

	private void initData() { 
		datas = new ArrayList<MarketStock>();
		topdatas = new ArrayList<MarketStock>();
		mQueue = Volley.newRequestQueue(getActivity().getApplicationContext());  
		mAdapter = new MarketAdapter(getActivity().getApplicationContext());
		actualListView.setAdapter(mAdapter);

		loadMarketDatas(stocktype,zqlb);
		mPullRefreshList();

	}
	
	private void mPullRefreshList(){
		mPullToRefreshListView.setRefreshing(true);
		mPullToRefreshListView.setMode(Mode.PULL_FROM_START);
		mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				Mode mode = mPullToRefreshListView.getCurrentMode(); 
				if(mode == Mode.PULL_FROM_START) {
					datas.clear();
					loadMarketDatas(stocktype,zqlb);
				}
			}
		});
	}

	@Override
	public void onClick(View v) { 
		Intent intent = new Intent();
		switch (v.getId()) {
		case R.id.ly_sh:
			intent.setClass(MarketContentFragment.this.getActivity(),MarketDeatilActivity.class);
			intent.putExtra("stockCode", topdatas.get(0).stock_code);
			Log.w("stockCode~~======!!!!", ""+topdatas.get(0).stock_code);
			intent.putExtra("stockName", topdatas.get(0).stock_name);
			startActivityForResult(intent,1);
			break;
		case R.id.ly_sz:
			intent.setClass(MarketContentFragment.this.getActivity(),MarketDeatilActivity.class);
			intent.putExtra("stockCode", topdatas.get(1).stock_code);
			intent.putExtra("stockName", topdatas.get(1).stock_name);			
			startActivityForResult(intent,1);
			break;
		case R.id.ly_cy:
			intent.setClass(MarketContentFragment.this.getActivity(),MarketDeatilActivity.class);
			intent.putExtra("stockCode", topdatas.get(2).stock_code);
			intent.putExtra("stockName", topdatas.get(2).stock_name);			
			startActivityForResult(intent,1);
			break;
		default:
			break;
		}
	}
	
	/**
	 * 行情列表页数据
	 * @param 股票类型 上证||深证
	 * @param 证券类别
	 */
	private void loadMarketDatas(final String stock_type,final String zqlb){
		String url = Statics.URL_PHP + Statics.IF_market;

		stringRequest = new CookieStringRequest(Method.POST,url, new Listener<String>() {

			@SuppressLint("NewApi") @Override
			public void onResponse(String response) {
				if(!TextUtils.isEmpty(response)){
//					Log.w("Market_Response!!!~", response);
					try {
						JSONObject obj = new JSONObject(response);
						if(obj.getInt("status") == 0){
							JSONObject dataobj = new JSONObject(obj.getString("data"));
							JSONArray msArray = dataobj.getJSONArray("detail");
							for(int i = 0 ; i < msArray.length() ; i ++){
								JSONObject msobj = msArray.getJSONObject(i);
								MarketStock ms = new MarketStock(msobj);
								datas.add(ms);
							}
							JSONArray topArray = dataobj.getJSONArray("category");
							for(int i = 0 ; i < topArray.length() ; i ++){
								JSONObject topobj = topArray.getJSONObject(i);
								MarketStock topms = new MarketStock(topobj);
								topdatas.add(topms);
							}
							if(null!=datas && datas.size()>0){
								mAdapter.datas = datas;
								mAdapter.notifyDataSetChanged(); 
							}
							if(null!=datas && datas.size()>0){
								TopHeadSetText();
							}
//							Log.w("MarketContent~~~mAdapter", mAdapter.datas.toString());
							mPullToRefreshListView.onRefreshComplete();
						}
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {
				// TODO Auto-generated method stub

			}
		}){
			@Override
			protected Map<String, String> getParams() throws AuthFailureError { 
				Map<String, String> params = new HashMap<String, String>();
				if(myApp.digitalid != null && !myApp.digitalid.equals("")){
					params.put("userID", myApp.digitalid);//userid 
					params.put("stock_type", stock_type);
					params.put("zqlb", zqlb);
				}
				return params;
			}
		};
		mQueue.add(stringRequest);
	}
	private OnItemClickListener itemClick = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) { 
			//			Toast.makeText(getApplicationContext(), position+","+id, Toast.LENGTH_SHORT).show();
			MarketStock ms = datas.get(position-2);
			Intent intent = new Intent(MarketContentFragment.this.getActivity(),MarketDeatilActivity.class);
			intent.putExtra("stockCode", ms.stock_code);
			intent.putExtra("stockName", ms.stock_name);
			intent.putExtra("inZixuangu", ms.inZixuangu);
			startActivityForResult(intent,1);
		}
	};

	/**
	 * 指数的设值 以及显示颜色等逻辑判断
	 */
	private void TopHeadSetText(){
		tv_sh_name.setText(topdatas.get(0).stock_name);
		tv_sh_price.setText(topdatas.get(0).new_price);
		String increment = FormatPrice(topdatas.get(0).old_price, 
				topdatas.get(0).new_price);
		tv_sh_increment.setText(increment);
		if(Float.valueOf(increment.substring(0, increment.length()-1))>= 0){
			tv_sh_price.setTextColor(getResources().getColor(R.color.kfColorRed));
			tv_sh_increment.setTextColor(getResources().getColor(R.color.kfColorRed));
		}else{
			tv_sh_price.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));
			tv_sh_increment.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));			
		}

		tv_sz_name.setText(topdatas.get(1).stock_name);
		tv_sz_price.setText(topdatas.get(1).new_price);
		String increment1 = FormatPrice(topdatas.get(1).old_price, 
				topdatas.get(1).new_price);
		tv_sz_increment.setText(increment1);
		if(Float.valueOf(increment1.substring(0, increment1.length()-1))>= 0){
			tv_sz_price.setTextColor(getResources().getColor(R.color.kfColorRed));
			tv_sz_increment.setTextColor(getResources().getColor(R.color.kfColorRed));
		}else{
			tv_sz_price.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));
			tv_sz_increment.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));			
		}

		tv_cy_name.setText(topdatas.get(2).stock_name);
		tv_cy_price.setText(topdatas.get(2).new_price);
		String increment2 = FormatPrice(topdatas.get(2).old_price, 
				topdatas.get(2).new_price);
		tv_cy_increment.setText(increment2);
		if(Float.valueOf(increment2.substring(0, increment2.length()-1))>= 0){
			tv_cy_price.setTextColor(getResources().getColor(R.color.kfColorRed));
			tv_cy_increment.setTextColor(getResources().getColor(R.color.kfColorRed));
		}else{
			tv_cy_price.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));
			tv_cy_increment.setTextColor(getResources().getColor(R.color.txtColorGreen_21d400));			
		}

	}

	private String FormatPrice(String oldprice,String newprice){
		DecimalFormat decimalFormat=new DecimalFormat("##0.00");
		Float old_price = Float.valueOf(oldprice);
		Float new_price = Float.valueOf(newprice);
		String increment = decimalFormat.format(((new_price - old_price)/old_price *100));

		return increment + "%";
	}

	private List<String> spinnerData(){
		List<String> list = new ArrayList<String>();
		list.add("上证指数");
		list.add("深证成指");
		list.add("创业板指");
		return list;
	}
}
